<template>
  <div class="add-or-edit">
    <Button type="primary" @click="handleClick">{{ isEdit?'编辑':'新增' }}</Button>
    <el-dialog :visible.sync="visible" :close-on-click-modal="false" :title="isEdit?'编辑':'新增'">
      <FormContainer :column="1">
        <el-form ref="form" :model="formData" :rules="formRules" :close-on-click-modal="false" label-width="80px">
          <el-form-item label="因子" prop="items">
            <el-checkbox-group v-model="formData.items">
              <el-checkbox v-for="(item,i) in combineElementData" :key="i" :label="item">{{ item.dictName }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="优先级" prop="level">
            <el-input v-model="formData.level" clearable placeholder="请输入优先级"></el-input>
          </el-form-item>
          <el-form-item :span="24">
            <div style="text-align: right;">
              <Button type="default" @click="handleCancel">取消</Button>
              <Button type="primary" @click="handleSave">保存</Button>
            </div>
          </el-form-item>
        </el-form>
      </FormContainer>
    </el-dialog>
  </div>
</template>
<script>
import FormContainer from '@/components/FormContainer'
import { create, update } from '@/api/elementCombine'
import { ccDict } from '@/api/dataDict'

export default {
  name: 'AddOrEdit',
  components: {
    FormContainer
  },
  props: {
    selection: {
      type: Array,
      default: () => []
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validatorLevel = (r, v, c) => {
      if (/^\d+$/.test(v)) {
        c()
      } else {
        c(new Error('优先级必填且只能是数字'))
      }
    }
    const validatorCombineElements = (r, v, c) => {
      if (v && v.length > 0) {
        c()
      } else {
        c(new Error('请选择因子'))
      }
    }
    return {
      combineElementData: [],
      visible: false,
      formData: {
        items: [],
        level: '' // 时效
      },
      formRules: {
        items: [{ required: true, validator: validatorCombineElements, trigger: 'change' }],
        level: [{ required: true, validator: validatorLevel, trigger: 'change' }]
      }
    }
  },
  computed: {
    detail() {
      return this.isEdit && this.selection instanceof Array && this.selection.length > 0 ? this.selection[0] : {}
    }
  },
  watch: {
    visible: {
      handler(v) {
        if (!v) {
          const form = this.$refs.form
          form && form.resetFields()
        } else if (this.isEdit && this.selection.length === 1) {
          const items = [];
          (this.detail.items || []).forEach(e => {
            const t = this.combineElementData.find(c => c.dictCode === e.factorCode)
            if (t) {
              items.push(t)
            }
          })
          this.$set(this.formData, 'items', items)
          const level = this.detail.level
          this.$set(this.formData, 'level', level === undefined || level === null ? '' : level)
        }
      },
      immediate: true
    }
  },
  created() {
    this.getCombineElement()
  },
  methods: {
    getCombineElement() {
      return ccDict('FACTOR_PROPERTY').then(res => {
        this.combineElementData = res.data
      })
    },
    handleClick() {
      if (this.isEdit) {
        if (this.selection.length > 1) {
          this.$message.warning(`该操作只能单选`)
          return
        } else if (this.selection.length === 0) {
          this.$message.warning(`请选择【编辑】项`)
          return
        }
      }
      this.visible = true
    },
    handleCancel() {
      this.visible = false
    },
    handleSave() {
      return this.$refs.form.validate().then(() => {
        return this.isEdit ? this.updateSaveData() : this.saveData()
      })
    },
    saveData() {
      this.formData.items.sort((prev, next) => {
        return prev.sort - next.sort
      })
      const items = this.formData.items.map(e => {
        return {
          factorCode: e.dictCode,
          factorName: e.dictName,
          factorSort: e.sort
        }
        // if (this.isEdit) {
        //   const item = this.detail.find(c => e.factorCode === e.dictCode)
        //   t.factorCombinationId = item.factorCombinationId
        //   t.id = item.id
        //   t.state = item.state
        // }
        // return t
      })
      const data = {
        items,
        level: this.formData.level
      }
      return create(data).then(res => {
        this.$message.success('操作成功!')
        this.visible = false
        this.$emit('on-refresh', 'onPage')
      })
    },
    updateSaveData() {
      this.formData.items.sort((prev, next) => {
        return prev.sort - next.sort
      })
      const data = {
        ...this.detail,
        level: this.formData.level
      }
      delete data.items
      delete data.combinationCode
      delete data.combinationName

      const items = []
      // 删除的
      this.detail.items.forEach(e => {
        const item = this.formData.items.find(i => i.dictCode === e.factorCode)
        if (!item) {
          items.push({
            ...e,
            dr: 1
          })
        }
      })

      this.formData.items.forEach(e => {
        const item = this.detail.items.find(i => e.dictCode === i.factorCode)
        if (!item) {
          // 新增的
          items.push({
            factorCode: e.dictCode,
            factorName: e.dictName,
            factorSort: e.sort
          })
        } else {
          // 已有的
          items.push({
            ...item,
            factorCode: e.dictCode,
            factorName: e.dictName,
            factorSort: e.sort
          })
        }
      })

      data.items = items
      return update(data).then(res => {
        this.$message.success('操作成功!')
        this.visible = false
        this.$emit('on-refresh', 'onPage')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.add-or-edit{
  display: inline-block;
  margin-right: 10px;
}
</style>
